﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ELMWCFServiceClass.ELMWCF;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.IO;
using ELMApplication.Common.Const;


namespace ELMApplication.Common.UC
{
    public partial class ExtendInfoUC : UserControl
    {
        ELMServiceClient _domainClient;
        public ExtendInfoUC()
        {
            InitializeComponent();

        }
        //数据缓存（图片，或者其他文件类型）
        public Dictionary<Guid, byte[]> FilesCache = new Dictionary<Guid, byte[]>();
        public void Load(Dictionary<ELMField, string> data)
        {

            foreach (var item in data)
            {
                TextBlock tb = new TextBlock();
                tb.FontSize = 14;
                tb.Height = 25;
                tb.TextAlignment = TextAlignment.Right;
                tb.Margin = new Thickness(0, 0, 3, 0);
                tb.Text = item.Key.FieldName;
                UIElement uielement = null;
                switch (item.Key.FieldType)
                {

                    case "SingleString":

                        uielement = CreateSingleString(item);

                        break;
                    case "Image":
                        tb.Cursor = Cursors.Hand;
                        tb.TextDecorations = TextDecorations.Underline;
                        tb.Margin = new Thickness(0, 5, 3, 76);
                        uielement = CreateImage(item,ref tb);

                        break;
                    case "RefList":
                        tb.Margin = new Thickness(0, 5, 3, 76);
                        CreateRefList(item);
                        break;
                    case "ComboList":
                        CreateComboList(item);
                        break;
                    case "MultString":
                        tb.Margin = new Thickness(0, 5, 3, 76);
                        uielement = CreateMultString(item);
                        break;
                    case "Int":
                        uielement = CreateInt(item);
                        break;
                    case "Double":
                        uielement = CreateDouble(item);
                        break;
                    case "DateTime":
                        uielement = CreateDateTime(item);
                        break;
                    case "YesOrNo":
                        uielement = CreateYesOrNo(item);
                        break;
                    case "User":

                        break;
                    case "UrlLink":

                        break;
                }
                labelPanel.Children.Add(tb);
                if (uielement != null)
                {
                    textPanel.Children.Add(uielement);
                }

            }


        }

        private void CreateRefList(KeyValuePair<ELMField, string> item)
        {
            ELMListUC elmuc = new ELMListUC();
            elmuc.SetGridHeight(100);
            elmuc.Margin = new Thickness(0, 3, 0, 2);
            elmuc.Tag = item.Key;
            elmuc.SetControl(false);
            if (item.Key.ItemSourceGuid.HasValue)
            {
                _domainClient = new ELMServiceClient();
                _domainClient.GetELMItemsByELMListIdAsync(item.Key.ItemSourceGuid.Value);
                _domainClient.GetELMItemsByELMListIdCompleted += (sender, data1) =>
                {
                    if (data1.Error == null)
                    {
                            
                            elmuc.LoadCommonData(data1.Result.First().ELMList.ContentType.ContentId,data1.Result);
                            //TextBlock tbtitle = new TextBlock();
                            //tbtitle.Text = data1.Result.First().ELMList.ELMListName + ":";
                           
                        
                    }
                };
            }
            textPanel.Children.Add(elmuc);
        }

        private Image CreateImage(KeyValuePair<ELMField, string> item, ref TextBlock tb)
        {

            Image image = new Image();
            image.HorizontalAlignment = HorizontalAlignment.Left;
            BitmapImage bmp = null;
            image.Width = 100; image.Height = 100;
            // image.Source = new BitmapImage(new Uri("/safe.png"));

            Guid imageId = Guid.Empty;
            if (!string.IsNullOrEmpty(item.Value))
            {
                imageId = new Guid(item.Value);
            }
            var tempdata = new Dictionary<ELMField, Guid>();
            tempdata.Add(item.Key, imageId);
            image.Tag = tempdata;
            _domainClient = new ELMServiceClient();
            _domainClient.GetRecourceAsync(imageId);
            _domainClient.GetRecourceCompleted += (sender, e) =>
            {
                if (e.Error == null && e.Result != null)
                {
                    MemoryStream ms = new MemoryStream(e.Result.FileData);
                    bmp = new BitmapImage();
                    bmp.SetSource(ms);
                    image.Source = bmp;
                }
            };
            tb.MouseLeftButtonUp += (sender, e) =>
            {
                sender = image;
                OpenFileDialog fd = new OpenFileDialog();
                fd.Filter = "图片文件|*.jpg";
                bool? bResult = fd.ShowDialog();
                if (null != bResult && bResult.Value)
                {

                    bmp = new BitmapImage();
                    FileStream fs = fd.File.OpenRead();

                    BinaryReader br = new BinaryReader(fs);
                    byte[] imageBuffer = new byte[br.BaseStream.Length];
                    br.Read(imageBuffer, 0, Convert.ToInt32(br.BaseStream.Length));
                    var dic = (Dictionary<ELMField, Guid>)((Image)sender).Tag;
                    Guid tempid = Guid.NewGuid();
                    if (dic[dic.First().Key] == Guid.Empty)
                    {
                        dic[dic.First().Key] = tempid;
                    }
                    else
                    {
                        tempid = dic[dic.First().Key];
                    }
                    FilesCache.Add(tempid, imageBuffer);
                    // imagevalue = System.Convert.ToBase64String(imageBuffer);
                    bmp.SetSource(fs);
                    fs.Close();
                    br.Close();


                    image.Source = bmp;



                }


            };

            return image;
        }

        private UIElement CreateSingleString(KeyValuePair<ELMField, string> item)
        {
            var i = item.Key.FieldName;

            TextBox tx = new TextBox();
            tx.Text = item.Value;
            tx.Height = 25;
            
            tx.Tag = item.Key;
            return tx;
        }

        private UIElement CreateYesOrNo(KeyValuePair<ELMField, string> item)
        {


            ComboBox tx = new ComboBox();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("否", bool.FalseString);
            dic.Add("是", bool.TrueString);
            tx.ItemsSource = dic;
            tx.DisplayMemberPath = "Key";
            if (!string.IsNullOrEmpty(item.Value) && dic.Any(c => c.Value == item.Value))
            {

                var sel = dic.Single(c => c.Value == item.Value);
                    tx.SelectedItem = sel;
                
            }
           
            tx.Height = 25;
            tx.HorizontalAlignment = HorizontalAlignment.Left;
            tx.Tag = item.Key;
            return tx;
        }

        private void CreateComboList(KeyValuePair<ELMField, string> item)
        {

            
            ComboBox tx = new ComboBox();
            if (item.Key.ItemSourceGuid.HasValue && item.Key.DisplayMemberGuid.HasValue)
            {
                _domainClient = new ELMServiceClient();
                _domainClient.GetELMItemsByELMListIdAsync(item.Key.ItemSourceGuid.Value);
                _domainClient.GetELMItemsByELMListIdCompleted += (sd, e) =>
                    {
                        if (e.Error != null) throw e.Error;
                        Dictionary<string, string> dic = new Dictionary<string, string>();
                        foreach (var tempitem in e.Result)
                        {
                            var thisdata=tempitem.Datas.First(c => c.Key.FieldId == item.Key.DisplayMemberGuid.Value);
                            if (!dic.Any(c => c.Key == thisdata.Value))
                            {
                                dic.Add(thisdata.Value, thisdata.Value);
                            }
                            
                        }
                        tx.ItemsSource = dic;
                        if (!string.IsNullOrEmpty(item.Value) && dic.Any(c => c.Value == item.Value))
                        {
                            tx.SelectedItem = dic.First(c => c.Value == item.Value);
                        }
                       
                        
                    };          
                
            }
            tx.Height = 25;
            tx.DisplayMemberPath = "Value";
            tx.HorizontalAlignment = HorizontalAlignment.Left;
            tx.Tag = item.Key;
            textPanel.Children.Add(tx);
            
        }

        

        private UIElement CreateDateTime(KeyValuePair<ELMField, string> item)
        {

            DatePicker tx = new DatePicker();
            tx.HorizontalAlignment = HorizontalAlignment.Left;
            tx.Text = item.Value;
            tx.Height = 25;
            tx.Tag = item.Key;
            tx.Width = 150;
            return tx;
        }
        private UIElement CreateInt(KeyValuePair<ELMField, string> item)
        {

            TextBox tx = new TextBox();
            string tempvalue = item.Value;
            if (string.IsNullOrEmpty(item.Value))
            {
                tempvalue = "0";
            }
            tx.Text = tempvalue;
            tx.Height = 25;
            tx.Tag = item.Key;
            tx.KeyDown += (sd, e) =>
            {
                if (tx.Resources["txt"]!=null)
                {
                    tx.Resources.Remove("txt");
                    tx.Resources.Add("txt", tx.Text);
                }
                else
                {
                    tx.Resources.Add("txt", tx.Text);
                }
            };

            tx.KeyUp += (sd, e) =>
                {
                    int tempint = 0;
                    if (tx.Text.Length > 0)
                    {
                        if (!int.TryParse(tx.Text, out tempint))//如果整个文本转换失败则开始遍历字符
                        {
                            tx.Text = tx.Resources["txt"].ToString();
                        }
                    }
                    //int i = 0;
                    //int tempint = 0;
                    //if (!int.TryParse(tx.Text, out tempint))//如果整个文本转换失败则开始遍历字符
                    //{
                    //    string newText = tx.Text;//新的文本
                    //    char[] newChars = newText.ToCharArray();
                    //    while (i <= newText.Length - 1)//遍历所有字符
                    //    {
                    //        if (!int.TryParse(newChars[i].ToString(), out tempint))//如果非INT
                    //        {
                    //            if (tx.Text.Length > 0)
                    //            {
                    //                int tempindex=tx.Text.IndexOf(newChars[i]);
                    //                tx.Text = tx.Text.Remove(tempindex, 1) ;
                    //            }
                    //        }
                    //        i++;
                    //    }
                    //}
                   
                };

            tx.LostFocus += (sd, e) =>
                {


                    if (tx.Text.Length == 0) tx.Text = "0";
                    else
                    {
                        int i = 0;
                        if (int.TryParse(tx.Text, out i))
                        {
                            tx.Text = i.ToString();
                        }
                    }
                };
            return tx;
        }

        private UIElement CreateDouble(KeyValuePair<ELMField, string> item)
        {

            TextBox tx = new TextBox();
            string tempvalue = item.Value;
            if (string.IsNullOrEmpty(item.Value))
            {
                tempvalue = "0";
            }
            tx.Text = tempvalue;
            tx.Height = 25;
            tx.Tag = item.Key;
            tx.KeyDown += (sd, e) =>
                {
                    if (tx.Resources["txt"] != null)
                    {
                        tx.Resources.Remove("txt");
                        tx.Resources.Add("txt", tx.Text);
                    }
                    else
                    {
                        tx.Resources.Add("txt", tx.Text);
                    }
                };
            tx.KeyUp += (sd, e) =>
            {var txts=tx.Text.ToCharArray();
            if (txts.Count(c => c.ToString() == ".") == 1&&txts.Last()=='.'&&txts.First()!='.')//只有1个点而且不是在第一位,而且是在最后一位
                {
                    return;
                }
                Double tempint = 0;
                if (tx.Text.Length > 0)
                {
                    if (!Double.TryParse(tx.Text, out tempint))//如果整个文本转换失败则开始遍历字符
                    {
                        tx.Text = tx.Resources["txt"].ToString();

                    }
                }
                

            };

            tx.LostFocus += (sd, e) =>
            {


                if (tx.Text.Length == 0) tx.Text = "0";
                else
                {
                    Double i = 0;
                    if (Double.TryParse(tx.Text.TrimEnd('.'), out i))
                    {
                        tx.Text = i.ToString();
                    }
                }
            };
            return tx;
        }
        private UIElement CreateMultString(KeyValuePair<ELMField, string> item)
        {
            TextBox tx = new TextBox();
            tx.Text = item.Value;
            tx.Height = 100;
            tx.AcceptsReturn = true;
            tx.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
            tx.Tag = item.Key;
            return tx;
        }
        public Dictionary<ELMField, string> GetFields()
        {
            Dictionary<ELMField, string> ds = new Dictionary<ELMField, string>();
            foreach (object tx in textPanel.Children)
            {
                if (tx is TextBox)
                {
                    TextBox tt = (TextBox)tx;
                    ds.Add((ELMField)tt.Tag, tt.Text);
                }
                else if (tx is Image)
                {
                    Image tt = (Image)tx;
                    Dictionary<ELMField, Guid> res = (Dictionary<ELMField, Guid>)tt.Tag;
                    ds.Add(res.First().Key, res.First().Value.ToString());
                }
                else if (tx is DatePicker)
                {
                    DatePicker dp = (DatePicker)tx;
                    ds.Add((ELMField)dp.Tag, dp.Text);
                }
                else if (tx is ComboBox)
                {
                    ComboBox cbb = (ComboBox)tx;
                    string newVariable = cbb.SelectedItem == null ? "" : ((KeyValuePair<string,string>)cbb.SelectedItem).Value;
                    ds.Add((ELMField)cbb.Tag, newVariable);
                }
                else if (tx is ELMListUC)
                {
                    ELMListUC uc = (ELMListUC)tx;
                    ds.Add((ELMField)uc.Tag, "");
                }
            }
            return ds;
        }
        public void ClearContent()
        {
            labelPanel.Children.Clear();
            textPanel.Children.Clear();
        }
    }
}
